﻿using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class CloudBoxController : ApiController
    {

        /*
         * 
         *from BillName  --订单类型
         *from PType_Price --商品 预售金额
         *from Custom_BillIndex --出库单自定义字段--客户姓名-电话
         */
        /// <summary>
        /// 查询云盒统计
        /// </summary>
        /// <param name="userrose">角色身份 (必传： 0 老板，1店长 ，2职员)</param>
        /// <param name="dusercode">部门 (非必传 当身份标识为店长“1”的时候传入)</param>
        /// <param name="eusercode">职员(非必传 当身份标识为职员“2”的时候传入)</param>
        /// <param name="yearth">年份（必传 年份如：2022）</param>
        /// <param name="monthth">月份(必传 月份如 ：3)</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectCloudBoxTol(dynamic dyobj)
        {
            Result1<DataTable> result = new Result1<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                result.jlrSum = "0";
                return Json(result);
            }

            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());


            //判断参数是否传入
            if (string.IsNullOrWhiteSpace(mydyobj.userrose.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "userrose角色身份不可为空";
                result.Data = null;
                result.jlrSum = "0";
                return Json(result);
            }


            if (string.IsNullOrWhiteSpace(mydyobj.yearth.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "yearth不可为空";
                result.Data = null;
                result.jlrSum = "0";
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(mydyobj.monthth.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "monthth不可为空";
                result.jlrSum = "0";
                result.Data = null;
                return Json(result);
            }

            if (!string.IsNullOrWhiteSpace(mydyobj.userrose.ToString()))
            {

                if (mydyobj.userrose.ToString() == "1")//店长
                {
                    if (string.IsNullOrWhiteSpace(mydyobj.dusercode.ToString()))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "身份是店长时,dusercode部门不可为空";
                        result.Data = null;
                        result.jlrSum = "0";
                        return Json(result);
                    }

                }
                else if (mydyobj.userrose.ToString() == "2")//职员
                {
                    if (string.IsNullOrWhiteSpace(mydyobj.eusercode.ToString()))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "身份是职员时,eusercode职员不可为空";
                        result.Data = null;
                        result.jlrSum = "0";
                        return Json(result);
                    }
                }

            }

            string strSQL;

            try
            {
                strSQL = "";


                //返回集合参数说明
                // fullname    类型名称  
                // monthTask   月任务      
                // endTask     截止任务
                // sumNum      销售数量
                // grossTotal  毛利总额
                // gapTask     截止任务差距


                if (mydyobj.userrose.ToString() == "2")//职员
                {
                    strSQL += " select fullname,UserCode,cast(round(monthTask,2) as numeric(20,2)) monthTask, ";
                    strSQL += " cast(round(endTask,2) as numeric(20,2)) endTask, ";
                    strSQL += " cast(round(sumNum,2) as numeric(20,2)) sumNum, ";
                    strSQL += " cast(round(grossTotal,2) as numeric(20,2)) grossTotal, ";
                    strSQL += " cast(round(gapTask,2) as numeric(20,2)) gapTask from( ";
                    strSQL += " select pt.fullname,pt.UserCode, isnull(mt.totalmoney,0) monthTask, ";
                    strSQL += " isnull((case when GETDATE() >= DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,GETDATE()),120)+ '1') then isnull(mt.totalMoney, 0) ";
                    strSQL += " else isnull(mt.totalMoney, 0)/day(dateadd(MONTH,1,GETDATE()-DAY(GETDATE())+1)-1)*DAY(GETDATE()) end),0) as endTask, ";
                    strSQL += " isnull(a.xiaoliang,0) sumNum, ";
                    strSQL += " isnull(a.maoli,0) grossTotal, ";
                    strSQL += " isnull((case when GETDATE() >= DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,GETDATE()),120) + '1') then isnull(mt.totalMoney, 0) ";
                    strSQL += " else isnull(mt.totalMoney,0)/day(dateadd(MONTH,1, GETDATE() - DAY(GETDATE()) + 1) - 1) * DAY(GETDATE()) end),0)-isnull(a.maoli, 0) gapTask ";
                    strSQL += " from PTypeCategory pt ";
                    strSQL += " left join (select p.PTypeCategoryid, sum(qty * -1) xiaoliang, sum(total * -1-CostTotal*-1 + ShareFee) maoli  from InOutstocktable ino ";
                    strSQL += " left join ptype p on ino.ptypeid = p.typeid ";
                    strSQL += " where ino.BillType in('11', '45') ";
                    strSQL += " and DATEPART(yyyy, ino.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and DATEPART(mm, ino.billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strSQL += " and etypeid=(select typeid from employee where usercode = '" + mydyobj.eusercode.ToString() + "') ";
                    strSQL += " GROUP BY PTypeCategoryid) as a on pt.typeid = a.PTypeCategoryid ";
                    strSQL += " left join MonthlyPerTasks mt on pt.typeid = mt.ptypeid ";
                    strSQL += " and years =" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and months =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strSQL += " and mt.etypeid=(select typeid from employee where usercode = '" + mydyobj.eusercode.ToString() + "') ";
                    strSQL += " where pt.soncount = 0 ) ttsaw";

                }
                else if (mydyobj.userrose.ToString() == "1")//店长
                {
                    strSQL += " select fullname,UserCode, cast(round(monthTask, 2) as numeric(20, 2)) monthTask, ";
                    strSQL += " cast(round(endTask, 2) as numeric(20, 2)) endTask, ";
                    strSQL += " cast(round(sumNum, 2) as numeric(20, 2)) sumNum, ";
                    strSQL += " cast(round(grossTotal, 2) as numeric(20, 2)) grossTotal, ";
                    strSQL += " cast(round(gapTask, 2) as numeric(20, 2)) gapTask from( ";
                    strSQL += " select pt.fullname,pt.UserCode, ";
                    strSQL += " isnull(mt.totalmoney, 0) monthTask, ";
                    strSQL += " isnull((case when GETDATE() >= DATEADD(Day, -1, CONVERT(char(8), DATEADD(Month, 1, GETDATE()), 120) + '1') then isnull(mt.totalMoney, 0) ";
                    strSQL += " else isnull(mt.totalMoney, 0)/day(dateadd(MONTH, 1, GETDATE() - DAY(GETDATE()) + 1) - 1) * DAY(GETDATE()) end),0) as endTask, ";
                    strSQL += " isnull(a.xiaoliang, 0) sumNum, ";
                    strSQL += " isnull(a.maoli, 0) grossTotal, ";
                    strSQL += " isnull((case when GETDATE() >= DATEADD(Day, -1, CONVERT(char(8), DATEADD(Month, 1, GETDATE()), 120) + '1') then isnull(mt.totalMoney, 0) ";
                    strSQL += " else isnull(mt.totalMoney, 0) / day(dateadd(MONTH, 1, GETDATE() - DAY(GETDATE()) + 1) - 1) * DAY(GETDATE()) end),0)-isnull(a.maoli, 0) gapTask ";
                    strSQL += " from PTypeCategory pt ";
                    strSQL += " left join (select p.PTypeCategoryid, sum(qty * -1) xiaoliang, sum(total * -1 - CostTotal * -1 + ShareFee) maoli  from InOutstocktable ino ";
                    strSQL += " left join ptype p on ino.ptypeid = p.typeid ";
                    strSQL += " where ino.BillType in('11', '45') ";
                    strSQL += " and DATEPART(yyyy, ino.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and DATEPART(mm, ino.billdate)=" + Convert.ToInt32(mydyobj.monthth.ToString());

                    strSQL += " and dtypeid=(select typeid from Department where usercode='" + mydyobj.dusercode.ToString() + "')";

                    strSQL += " GROUP BY PTypeCategoryid) as a on pt.typeid = a.PTypeCategoryid ";
                    strSQL += " left join MonthlyTasks mt on pt.typeid = mt.ptypeid ";
                    strSQL += " and years=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and months=" + Convert.ToInt32(mydyobj.monthth.ToString());

                    strSQL += " and mt.dtypeid=(select typeid from Department where usercode='" + mydyobj.dusercode.ToString() + "')";


                    strSQL += " where pt.soncount = 0 ) tttt";
                }
                else if (mydyobj.userrose.ToString() == "0")//老板
                {
                    strSQL += "  select fullname,UserCode,";
                    strSQL += "  cast(round(totalmoney, 2) as numeric(20, 2)) monthTask,";
                    strSQL += "  cast(round(jiezhirenwu, 2) as numeric(20, 2)) endTask,";
                    strSQL += "  cast(round(xiaoliang, 2) as numeric(20, 2)) sumNum,";
                    strSQL += "  cast(round(maoli, 2) as numeric(20, 2)) grossTotal,";
                    strSQL += "  (jiezhirenwu - maoli) gapTask ";
                    strSQL += " from(select pt.fullname,pt.UserCode, isnull(b.totalmoney, 0) totalmoney,";
                    strSQL += " isnull((case when GETDATE() >= DATEADD(Day, -1, CONVERT(char(8), DATEADD(Month, 1, GETDATE()), 120) + '1') then isnull(b.totalMoney, 0) ";
                    strSQL += " else isnull(b.totalMoney, 0)/day(dateadd(MONTH,1,GETDATE()-DAY(GETDATE()) + 1) - 1) * DAY(GETDATE()) end), 0) as jiezhirenwu,";
                    strSQL += " isnull(a.xiaoliang, 0) xiaoliang,isnull(a.maoli, 0) maoli";
                    strSQL += " from PTypeCategory pt";
                    strSQL += " left join (select p.PTypeCategoryid, sum(qty * -1) xiaoliang, sum(total * -1 - CostTotal * -1 + ShareFee) maoli  from InOutstocktable ino";
                    strSQL += " left join Department d on ino.DTypeID=d.typeid";//2022-06-06增加部门条件
                    strSQL += " left join ptype p on ino.ptypeid = p.typeid";
                    strSQL += " where ino.BillType in('11', '45')";
                    strSQL += " and DATEPART(yyyy, ino.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and DATEPART(mm, ino.billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strSQL += " and d.Fax='88888'";//2022-06-06增加部门条件
                    strSQL += " GROUP BY PTypeCategoryid) as a on pt.typeid = a.PTypeCategoryid";
                    strSQL += " left join (select pt.typeid, sum(isnull(mt.totalmoney, 0)) totalmoney from PTypeCategory pt";
                    strSQL += " left join MonthlyTasks mt on pt.typeid = mt.ptypeid and years=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strSQL += " and months =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strSQL += " GROUP BY pt.typeid) as b on pt.typeid = b.typeid";
                    strSQL += " where pt.soncount = 0) ttt";
                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "userrose参数值错误";
                    result.Data = null;
                    result.jlrSum = "0";
                    return Json(result);
                }
                decimal m = 0;
                decimal j = 0;
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
                if (mydyobj.userrose.ToString() == "0" || mydyobj.userrose.ToString() == "1")
                {
                    //获取净利润总和
                    string strsql1 = "";
                    strsql1 += " ";

                    strsql1 += " with A as( ";
                    strsql1 += " select ";
                    strsql1 += " d.typeid as dtypeid ";
                    strsql1 += " ,d.fullname ";
                    strsql1 += " ,p.totalMoney ";
                    strsql1 += " ,ISNULL(T.Profit, 0) as mlSum ";
                    strsql1 += " ,ISNULL(G.gd, 0) AS gd ";
                    strsql1 += "  , ISNULL((select sum(total) from billindex bi ";
                    strsql1 += " left join moneybill mb on bi.billnumberid=mb.billnumberid where bi.billtype in(158,36) and RedWord=0 and draft=0  ";
                    strsql1 += " and mb.atypeid in (select nid from Ac_Items where nparid like '00004000030001300008%')  ";
                    strsql1 += " and mb.dtypeid = d.typeid ";
                    strsql1 += " and DATEPART(yyyy, billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and DATEPART(mm, billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " ),0) as rc ";
                    strsql1 += " ,ISNULL((select sum(total) from billindex bi ";
                    strsql1 += " left join moneybill mb on bi.billnumberid=mb.billnumberid where bi.billtype in(158,36) and RedWord=0 and draft=0  ";
                    strsql1 += " and mb.atypeid in (select nid from Ac_Items where nparid like '00004000030001300007%') ";
                    strsql1 += " and mb.dtypeid = d.typeid ";
                    strsql1 += " and DATEPART(yyyy, billdate)= " + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and DATEPART(mm, billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " ),0) as hd ";
                    strsql1 += "   ,ISNULL((select sum(hjgz) from (select bmid,isnull(dixin,0)+isnull(((select isnull(sum(total*-1),0)-isnull(sum(costtotal*-1),0) + ISNULL(SUM(ios.ShareFee),0) maoli from InOutstocktable ios  ";
                    strsql1 += " left join ptype p on ios.ptypeid = p.typeid  ";
                    strsql1 += " left join PTypeCategory pc on p.PTypeCategoryid = pc.typeid ";
                    strsql1 += " where billtype in (11, 45) and pc.typeid in ('00001','00002', '00003', '00004', '00005', '00006', '00007', '00008', '00009', '00010', '00011', '00012','00013','00014') and ios.etypeid = c.typeid ";
                    strsql1 += " and DATEPART(yyyy, billdate) =" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and DATEPART(mm, billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " )*tichenglv),0) hjgz from (select ( ";
                    strsql1 += " select top 1 Proportion from CommissionRuleRegion cr where b.typeid=cr.etypeid and MinRegion<zongmaoli order by MinRegion desc)/100  tichenglv,* ";
                    strsql1 += " from( ";
                    strsql1 += " select d.typeid bmid,d.fullname bumen,e.fullname zhiyuan,e.typeid, ";
                    strsql1 += " case when costom1='' then 0 else isnull(costom1,0) end dixin,(a.total-a.costtotal) zongmaoli ";
                    strsql1 += " from employee e ";
                    strsql1 += " left join Etype_CustomColumns ec on e.typeid=ec.typeid ";
                    strsql1 += " left join Department d on e.dtypeid=d.typeid ";
                    strsql1 += " left join (select etypeid,sum(total*-1) total,sum(costtotal*-1) costtotal ";
                    strsql1 += " from InOutstocktable ios ";
                    strsql1 += " left join ptype p on ios.ptypeid=p.typeid ";
                    strsql1 += " where billtype in (11, 45) ";
                    strsql1 += " and DATEPART(yyyy, billdate) =" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and DATEPART(mm, billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " GROUP BY etypeid) as a on e.typeid=a.etypeid ";
                    strsql1 += " where d.soncount=0 and e.sonnum=0 ) as b) as c) as bm where bmid=d.typeid  ";
                    strsql1 += " ),0) as ry  ";

                    strsql1 += " ,convert(int,day( dateadd(day,-1, dateadd(month,1,convert(char(07),getdate(),120)+'-01')))) as days ";
                    strsql1 += " from Department d ";
                    strsql1 += " left ";
                    strsql1 += " join (select dtypeid,totalMoney from ProfitTasks ";
                    strsql1 += " where 1 = 1  ";
                    strsql1 += "  and years=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += "  and months=" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " ) P on P.dtypeid = d.typeid ";

                    string newdate = "";
                    if (mydyobj.monthth.ToString() != "10" || mydyobj.monthth.ToString() != "11" || mydyobj.monthth.ToString() != "12")
                    {
                        newdate = mydyobj.yearth.ToString() + "-" + "0" + mydyobj.monthth.ToString() + "-01";
                    }
                    else
                    {
                        newdate = mydyobj.yearth.ToString() + "-" + mydyobj.monthth.ToString() + "-01";
                    }

                    strsql1 += " left join ( ";
                    strsql1 += " select dtypeid,(totalMoney / day(dateadd(month, 1, '" + newdate + "') - 1)) * DATEPART(DAY, GETDATE()) as gd ";
                    strsql1 += " from FixedTasks ";
                    strsql1 += " where 1 = 1 ";
                    strsql1 += " and years = " + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and months =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " ) as G on G.dtypeid = d.typeid ";

                    strsql1 += " left join ";
                    strsql1 += " (select ";
                    strsql1 += " d.typeid as Did ";
                    strsql1 += " , d.FullName as Dname ";
                    strsql1 += " , SUM(io.Qty * -1) as Qty ";
                    strsql1 += " , SUM(ISNULL(total, 0) * -1)-SUM(ISNULL(costtotal,0)* -1) + ISNULL(SUM(io.ShareFee),0) AS Profit ";
                    strsql1 += " from Department AS d ";

                    strsql1 += "  left join InOutstocktable as io on io.DTypeID = d.typeid ";
                    strsql1 += "  left join Ptype as p on io.PtypeId = p.typeId ";
                    strsql1 += "  left join PTypeCategory as pc on pc.typeid = p.PtypeCategoryID ";

                    strsql1 += "  where 1 = 1 ";
                    strsql1 += " and io.BillType in('11', '45')  ";
                    strsql1 += " and DATEPART(yyyy, io.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                    strsql1 += " and DATEPART(mm, io.billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                    strsql1 += " and  d.soncount = 0 ";
                    strsql1 += " and pc.typeid in ('00001','00002','00003','00004','00005','00006','00007','00008','00009','00010','00011','00012','00013','00014')  ";
                    strsql1 += "  GROUP BY d.typeid,d.FullName ";
                    strsql1 += " ) as T on T.Did = d.typeid ";
                    strsql1 += " where d.soncount = 0 ";
                    strsql1 += " and d.Fax = '88888' ";
                    if (mydyobj.userrose.ToString() == "1")//店长
                    {
                        strsql1 += " and d.typeid =(select typeid from Department where usercode='" + mydyobj.dusercode.ToString() + "')"; //部门条件
                    }
                    strsql1 += " )  ";
                    strsql1 += " select ";
                    strsql1 += " A.dtypeid ";
                    strsql1 += " ,A.FullName ";
                    strsql1 += " ,A.totalMoney ";
                    strsql1 += " ,A.mlSum ";
                    strsql1 += " ,A.gd ";
                    strsql1 += " ,A.rc ";
                    strsql1 += " ,A.hd ";
                    strsql1 += " ,A.ry ";
                    strsql1 += " ,(A.gd + A.rc + A.hd + A.ry) hjSum ";
                    strsql1 += " ,(A.mlSum - (A.gd + A.rc + A.hd + A.ry)) as jlrSum ";// --净利润 

                    strsql1 += " ,ISNULL(((A.mlSum - (A.gd +A.rc + A.hd + A.ry))/  ";
                    strsql1 += " nullif((case when GETDATE()>=DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,GETDATE()),120)+'1')  ";
                    strsql1 += " then isnull(A.totalMoney, 0) ";
                    strsql1 += " else isnull(A.totalMoney,0)/day(dateadd(MONTH,1,GETDATE()-DAY(GETDATE())+1)-1)*DAY(GETDATE()) end),0) ";
                    strsql1 += " ),0) as jiezhizhanbi ";

                    strsql1 += " ,ISNULL((A.mlSum - (A.gd +A.rc + A.hd + A.ry))/NULLIF(A.totalMoney,0),0) as yuezhanbi ";

                    strsql1 += " ,(case when GETDATE()>=DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,GETDATE()),120)+'1') then isnull(A.totalMoney,0) ";
                    strsql1 += " else isnull(A.totalMoney,0)/day(dateadd(MONTH,1,GETDATE()-DAY(GETDATE())+1)-1)*DAY(GETDATE()) end)-(A.mlSum-(A.gd +A.rc + A.hd + A.ry)) as jiezhichaju ";

                    strsql1 += " ,(case when GETDATE()>=DATEADD(Day,-1,CONVERT(char(8),DATEADD(Month,1,GETDATE()),120)+'1') then isnull(A.totalMoney,0) ";
                    strsql1 += " else isnull(A.totalMoney,0)/day(dateadd(MONTH,1,GETDATE()-DAY(GETDATE())+1)-1)*DAY(GETDATE()) end) as jiezhirenwu ";
                    strsql1 += " from A ";
                    DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strsql1).Tables[0];

                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        j += Convert.ToDecimal(dt2.Rows[i]["jlrSum"]);
                        m += Convert.ToDecimal(dt2.Rows[i]["mlSum"]);
                    }
                }
                else
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        m += Convert.ToDecimal(dt.Rows[i]["grossTotal"]);
                    }
                }

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
                result.jlrSum = Math.Round(j, 2).ToString();//按照四舍五入的国际标准m.ToString();
                result.mlSum = Math.Round(m, 2).ToString();
                result.TotalRows = dt.Rows.Count;

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                result.jlrSum = "0";
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 查询云盒统计详情
        /// </summary>
        /// <param name="userrose">角色身份 (必传： 0 老板，1店长 ，2职员  例如：0)</param>
        /// <param name="dusercode">部门 (非必传 当身份标识为店长“1”的时候传入  例如：105)</param>
        /// <param name="eusercode">职员(非必传 当身份标识为职员“2”的时候传入   例如：24446)</param>
        /// <param name="ptypecode">类型(必传  例如：01)</param>
        /// <param name="yearth">年份（必传 例如：2022）</param>
        /// <param name="monthth">月份(必传 例如 ：3)</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectCloudBoxDetail(dynamic dyobj)
        {
            Result<DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            int pagesize = 10;
            int pageindex = 1;

            //判断参数是否传入
            if (string.IsNullOrWhiteSpace(mydyobj.userrose.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "userrose角色身份不可为空";
                result.Data = null;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(mydyobj.ptypecode.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "ptypecode类型不可为空";
                result.Data = null;
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(mydyobj.yearth.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "yearth年份不可为空";
                result.Data = null;
                return Json(result);
            }
            if (string.IsNullOrWhiteSpace(mydyobj.monthth.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "monthth月份不可为空";
                result.Data = null;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(mydyobj.pagesize.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "pagesize不可为空";
                result.Data = null;
                return Json(result);
            }
            else
            {
                pagesize = Convert.ToInt32(mydyobj.pagesize.ToString());
            }


            if (string.IsNullOrWhiteSpace(mydyobj.pageindex.ToString()))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "pageindex不可为空";
                result.Data = null;
                return Json(result);
            }
            else
            {
                pageindex = Convert.ToInt32(mydyobj.pageindex.ToString());
            }

            if (!string.IsNullOrWhiteSpace(mydyobj.userrose.ToString()))
            {

                if (mydyobj.userrose.ToString() == "1")//店长
                {
                    if (string.IsNullOrWhiteSpace(mydyobj.dusercode.ToString()))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "身份是店长时,dusercode不可为空";
                        result.Data = null;
                        return Json(result);
                    }

                }
                else if (mydyobj.userrose.ToString() == "2")//职员
                {
                    if (string.IsNullOrWhiteSpace(mydyobj.eusercode.ToString()))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "身份是职员时,eusercode不可为空";
                        result.Data = null;
                        return Json(result);
                    }
                }

            }


            //返回集合参数说明
            // billcode    单号      1
            // pname       商品      1
            // qty         数量      5
            // total       价格      195
            // bname       客户名称  张三
            // ename       店员名称  李四
            // department  部门名称 一部
            // posttime    订单时间 2022-06-14

            string strSQL;

            try
            {
                strSQL = "";
                strSQL += " declare @pagesize int; ";
                strSQL += " declare @pageindex int; ";
                strSQL += " set @pagesize =" + pagesize + ";";
                strSQL += " set @pageindex = " + pageindex + "; ";
                strSQL += "  select* from (select ROW_NUMBER() over(order by posttime desc) as 'rowNumber', *from ";
                strSQL += " ( ";

                strSQL += " select ";
                strSQL += " bi.billcode,";
                strSQL += " p.fullname pname, ";
                strSQL += " cast(ino.qty*-1 as int) qty,";
                strSQL += " cast(round(ino.total*-1,2) as numeric(20,2)) total, ";
                strSQL += " cb.SysDiy1_head bname,cb.SysDiy2_head btel,";
                strSQL += " e.fullname ename,";
                strSQL += " e.Tel etel,";
                strSQL += " e.department,";
                strSQL += " bi.posttime ";
                strSQL += " from InOutstocktable ino ";
                strSQL += " left join ptype p on ino.ptypeid = p.typeid ";
                strSQL += " left join billindex bi on ino.billnumberid = bi.billnumberid ";
                strSQL += " left join Custom_BillIndex cb on cb.BillId = bi.BillNumberId ";
                strSQL += " left join btype b on ino.btypeid = b.typeid ";
                strSQL += " left join employee e on ino.etypeid = e.typeid ";
                strSQL += " where ino.BillType in('11','45') ";
                strSQL += " and DATEPART(yyyy, ino.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                strSQL += " and DATEPART(mm, ino.billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                strSQL += " and p.PTypeCategoryid = (select typeid from PTypeCategory where usercode = '" + mydyobj.ptypecode.ToString() + "') ";//商品类别
                //--老板传空   店长传部门 店员传职员   选择改变条件
                if (mydyobj.userrose.ToString() == "1")//店长
                {
                    strSQL += " and ino.dtypeid=(select typeid from Department where usercode='" + mydyobj.dusercode.ToString() + "') ";//--店长传部门 
                }
                if (mydyobj.userrose.ToString() == "2")//职员
                {
                    strSQL += " and ino.etypeid =(select typeid from employee where usercode='" + mydyobj.eusercode.ToString() + "') ";//--店员传职员 
                }

                strSQL += " )t) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize) ";
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];



                string strSQL1 = "";
                strSQL1 += " select count(*) ";
                strSQL1 += " from InOutstocktable ino ";
                strSQL1 += " left join ptype p on ino.ptypeid = p.typeid ";
                strSQL1 += " left join billindex bi on ino.billnumberid = bi.billnumberid ";
                strSQL1 += " left join Custom_BillIndex cb on cb.BillId = bi.BillNumberId ";
                strSQL1 += " left join btype b on ino.btypeid = b.typeid ";
                strSQL1 += " left join employee e on ino.etypeid = e.typeid ";
                strSQL1 += " where ino.BillType in('11','45') ";
                strSQL1 += " and DATEPART(yyyy, ino.billdate)=" + Convert.ToInt32(mydyobj.yearth.ToString());
                strSQL1 += " and DATEPART(mm, ino.billdate) =" + Convert.ToInt32(mydyobj.monthth.ToString());
                strSQL1 += " and p.PTypeCategoryid = (select typeid from PTypeCategory where usercode = '" + mydyobj.ptypecode.ToString() + "') ";//商品类别
                //--老板传空   店长传部门 店员传职员   选择改变条件
                if (mydyobj.userrose.ToString() == "1")//店长
                {
                    strSQL1 += " and ino.dtypeid=(select typeid from Department where usercode='" + mydyobj.dusercode.ToString() + "') ";//--店长传部门 
                }
                if (mydyobj.userrose.ToString() == "2")//职员
                {
                    strSQL1 += " and ino.etypeid =(select typeid from employee where usercode='" + mydyobj.eusercode.ToString() + "') ";//--店员传职员 
                }

                int countT = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(strSQL1));


                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;

                result.TotalRows = countT;

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 同价调拨单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IHttpActionResult CreateAllocationOrder(BaseBillIndexModel model)
        {


            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            //职员ID
            if (string.IsNullOrWhiteSpace(model.Eusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Eusercode不可为空";
                return Json(result);
            }
            //入仓库
            if (string.IsNullOrWhiteSpace(model.InKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }
            //出仓库
            if (string.IsNullOrWhiteSpace(model.OutKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }

            //订单Code
            if (string.IsNullOrWhiteSpace(model.Billcode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Billcode不可为空";
                return Json(result);
            }

            //查询职员ID
            string strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Eusercode);
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();
            string Fullname = dt.Rows[0]["FullName"].ToString();


            //查询入库仓库ID
            string strSQL2 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.InKusercode);
            DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
            if (dt2.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "入库仓库ID不存在";
                return Json(result);
            }
            string inKtypeid = dt2.Rows[0]["typeid"].ToString();



            //查询出库仓库ID
            string strSQL8 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.OutKusercode);
            DataTable dt8 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL8).Tables[0];
            if (dt8.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "出库仓库ID不存在";
                return Json(result);
            }
            string outKtypeid = dt8.Rows[0]["typeid"].ToString();


            //判断商品Billcode是否存在
            string strSQL7 = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Billcode);
            DataTable dt7 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL7).Tables[0];
            if (dt7.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:Billcode已存在";
                return Json(result);
            }
            if (model.CommoditiesDetails.Count > 0)
            {
                foreach (var item in model.CommoditiesDetails)
                {

                    //商品
                    if (string.IsNullOrWhiteSpace(item.Pusercode))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "CommoditiesDetails.Pusercode商品类型code不可为空";
                        return Json(result);
                    }
                }

            }
            else
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "未添加商品明细";
                return Json(result);
            }

            decimal pricetotal = 0;
            for (int i = 0; i < model.CommoditiesDetails.Count; i++)
            {
                //查询商品ID
                string strSQL23 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[i].Pusercode.Trim());
                DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];

                if (dt23.Rows.Count > 0)
                {

                    DataTable dt22 = null;
                    string strSQL22 = "";
                    if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[i].Serial))
                    {
                        //仓库表单价
                        strSQL22 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt23.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }
                    else
                    {
                        //序列号表单价
                        strSQL22 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[i].Serial + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }

                    if (dt22.Rows.Count > 0)
                    {
                        pricetotal += (Convert.ToDecimal(dt22.Rows[0]["Price"].ToString()) * model.CommoditiesDetails[i].CQty);
                    }
                    else
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "商品没有录入价格，请完善商品Pusercode基本信息:" + model.CommoditiesDetails[i].Pusercode.Trim();
                        return Json(result);
                    }

                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "商品明细有不存在的商品，请检查商品Pusercode参数值是否准确：" + model.CommoditiesDetails[i].Pusercode.Trim();
                    return Json(result);
                }

                if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[i].InCargoCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "CargoCode[" + model.CommoditiesDetails[i].InCargoCode + "]不存在，或此仓库没有这个货位";
                    return Json(result);
                }
                if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[i].OutCargoCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "CargoCode[" + model.CommoditiesDetails[i].OutCargoCode + "]不存在，或此仓库没有这个货位";
                    return Json(result);
                }


            }




            try
            {

                string BillIndexNumberId = "";//单号 

                string nowda = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string code = model.Billcode.ToString();
                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",Convert.ToDateTime(nowda)),//单据日期
                    new SqlParameter("@BillCode",model.Billcode),//单据编码
                    new SqlParameter("@BillType","17"),////单据类型 17调拨单
                    new SqlParameter("@Comment", "根据单号【" + code + "】生成调拨单"),//备注
                    new SqlParameter("@ATypeID",""),//会计科目ID  Atype表 0000100006
                    new SqlParameter("@PTypeID",""),//商品ID Ptype表
                    new SqlParameter("@BTypeID", ""),//往来单位ID 暂时默认00001 20220421去掉 00001     
                    new SqlParameter("@ETypeID", Etypeid),//职员ID
                    new SqlParameter("@KTypeID", outKtypeid),//出库仓库ID
                    new SqlParameter("@KTypeID2",inKtypeid),//入库仓库ID   
                    new SqlParameter("@IfCheck", "f"),//是否过账标识 't','f'
                    new SqlParameter("@CheckE",Etypeid),//制单人
                    new SqlParameter("@TotalMoney","0"),//单据金额
                    new SqlParameter("@TotalQty",model.CommoditiesDetails.Sum(p => p.CQty)),//单据数量
                    new SqlParameter("@ntotalmoney", "0"),//原币总金额 //合计
                    new SqlParameter("@TotalInMoney",pricetotal),//收款金额
                    new SqlParameter("@Tax","0.0"),//税率0.0
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@ATYPEID1", ""),//往来科目
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount","0"),//是否多账户收(付)款
                    new SqlParameter("@vipczmoney", "0"),//充值前金额
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//会员卡充值前次数 维修的
                    new SqlParameter("@PosBillType","0"),//
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney","0"),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@sharemode","0"),//摊销方式
                    new SqlParameter("@DEALBTYPEID",""),//往来单位 20220421去掉00001
                    new SqlParameter("@cid",1),//外币币种id
                    new SqlParameter("@rate", 1),//汇率
                    new SqlParameter("@ntotalinmoney", "0"),//原币收现金额
                    new SqlParameter("@npreferencemoney", "0"),//原币优惠金额
                    new SqlParameter("@nvipczmoney", "0"),//原币会员卡充值金额
                    new SqlParameter("@billproperty", -1),//单据属性
                    new SqlParameter("@ncompletetotal", "0"),//原币结算金额
                    new SqlParameter("@isini", false),//是否是期初 
                    new SqlParameter("@ATID","0"),//
                    new SqlParameter("@completetotal", "0"),//按单结算金额
                    new SqlParameter("@IfCargo", "0"),//是否启用货位调整
                    new SqlParameter("@IfInvoice","0"),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//
                    new SqlParameter("@WayBillCode", ""),//运单号
                    new SqlParameter("@Goodsnumber", ""),//物件数量 
                    new SqlParameter("@PackWay", ""),//包装方式 
                    new SqlParameter("@Tel", ""),//电话 这个应该是货运公司
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//接件单id
                    new SqlParameter("@JieJianID","-1"),//接件单明细id
                    new SqlParameter("@BaoXiuID","-1"),//报修单明细id
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//报修单id
                   /////////////////////////////////////////////////////////////////
                  
                    new SqlParameter("@OrderID","0"),//订单ID  
                    new SqlParameter("@preferencemoney","0"),//优惠金额 
                    new SqlParameter("@AlertDay", 9999),//收付款日期   
                    new SqlParameter("@VipCardID", -1),//vip卡id 
                    new SqlParameter("@KTypeID3",""),//维修仓库
                    new SqlParameter("@LinkMan", ""),//联系人
                    new SqlParameter("@LinkTel", ""),//联系电话
                    new SqlParameter("@LinkAddr",""),//联系地址
                    new SqlParameter("@wxManID",""),//维修人卡号      
                    new SqlParameter("@BuyDate",""),//会员卡有效期 datetime
                    new SqlParameter("@Serial",  ""),//序列号 
                    new SqlParameter("@wxTotal","0"),// 充值次数,金额 
                    new SqlParameter("@ErrDes",""),//故障描述
                    new SqlParameter("@ifHideJieJian", "0"),//是否隐
                    new SqlParameter("@ifWX","0"),//是否维修单据
                    new SqlParameter("@IfBargainOn","0"),//询价单，报价单成交标志 /// 0:未成交 1:成交
                    new SqlParameter("@FromBillNumberID", "0"),//源单id
                    new SqlParameter("@CostSale","0"),//成本价销售标识
                    new SqlParameter("@uf1",""),////自定义表头字段
                    new SqlParameter("@uf2",""),//
                    new SqlParameter("@uf3",""),//
                    new SqlParameter("@uf4",""),//
                    new SqlParameter("@uf5", ""),//
                    new SqlParameter("@invoicemoney", "0"),//已开票本币金额
                    new SqlParameter("@ninvoicemoney", "0"),//已开票原币金额
                    //new SqlParameter("@importtype", 0),//TINYINT类型
                    new SqlParameter("@AssetBusinessTypeId", "0"),////业务类型id     
                    new SqlParameter("@discount", 1),//折扣
                    new SqlParameter("@checkSave", ""),//
                    new SqlParameter("@chargeoffbtypeid", ""),//
                   // new SqlParameter("@chargeofftype", 0),//
                    new SqlParameter("@chargeofftotal", "0"),//
                    new SqlParameter("@nchargeofftotal", "0"),//
                    new SqlParameter("@IsLend", "0"),//     
                    new SqlParameter("@PromonIds", ""),//
                    new SqlParameter("@isByBrandarType", "0"),//是否启用品牌             
	                new SqlParameter("@promotionmsg", ""),//
                    new SqlParameter("@STypeID2", ""),//
                   // new SqlParameter("@ifconfirm", 0),//
                  //  new SqlParameter("@FeeDeductType", 0),//
                    new SqlParameter("@TransferType", 1),//
                    new SqlParameter("@isyapi", "0"),//
                    new SqlParameter("@yapiorderid","0"),//
                    new SqlParameter("@DeliveryAddress",""),//
                   // new SqlParameter("@AdpriceType", 0),//
                    new SqlParameter("@WarehouseOutDay", 9999),//出库期限
                    new SqlParameter("@StockInDeadline", 9999),//入库期限
                    new SqlParameter("@IsNeedTransport", 0),//是否需要运输配送
                    new SqlParameter("@iscombinationstyle", "0"),//
                    new SqlParameter("@transporterid", "0"),//
                    new SqlParameter("@transporterfullname", ""),//
                    new SqlParameter("@shipperfullname", ""),//
                    new SqlParameter("@shipperperson", ""),//
                    new SqlParameter("@shippertel", ""),//
                    new SqlParameter("@transportno", ""),//
                    new SqlParameter("@totalfreight", "0"),//
                    new SqlParameter("@ntotalfreight","0"),//
                    new SqlParameter("@NewPosBill", 0),//pos上传单据标志
                  //  new SqlParameter("@PayOnTheSpot", 0),//当面付
                    new SqlParameter("@posid", 0),//
                    new SqlParameter("@allowinvoicing", 1)//
     
                };


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                DataTable dt6 = new DataTable();
                string strSQL6 = "";
                strSQL6 += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(code);
                dt6 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL6).Tables[0];
                if (dt6.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                //获取单号
                BillIndexNumberId = dt6.Rows[0]["BillNumberId"].ToString();




                //执行添加调拨明细
                if (model.CommoditiesDetails.Count > 0)
                {
                    string ssql = "declare @p1 dbo.TBType_MoveBill ";
                    for (int j = 0; j < model.CommoditiesDetails.Count; j++)
                    {
                        //查询出库货位
                        string strSQL3 = "select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[j].OutCargoCode + "'";
                        DataTable dt3 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        string outhuowei = dt3.Rows[0]["CargoID"].ToString();

                        //查询入库货位
                        string strSQL9 = "select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[j].InCargoCode + "'";
                        DataTable dt9 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL9).Tables[0];
                        string inhuowei = dt9.Rows[0]["CargoID"].ToString();

                        //查询商品ID
                        string strSQL20 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[j].Pusercode.Trim());
                        DataTable dt20 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL20).Tables[0];


                        //查询商品ID

                        DataTable dt21 = null;
                        string strSQL21 = "";
                        if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[j].Serial))
                        {
                            //仓库表单价
                            strSQL21 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt20.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }
                        else
                        {
                            //序列号表单价
                            strSQL21 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[j].Serial + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }



                        ssql += @"insert into @p1 values(N'" + BillIndexNumberId + @"',
                                                                     N'" + dt20.Rows[0]["typeid"].ToString() + @"',
                                                                     N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                                                                     N'" + dt21.Rows[0]["Price"].ToString() + @"',
                                                                     N'" + (Convert.ToDecimal(dt21.Rows[0]["Price"].ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                                                                     N'',
                                                                     N'0',
                                                                     N'я" + model.CommoditiesDetails[j].Serial.ToString().Replace(",", "я") + @"я',
                                                                     N'0',
                                                                     N'" + dt21.Rows[0]["GoodsNumber"].ToString() + @"',
                                                                     N'" + dt21.Rows[0]["ProduceDate"].ToString() + @"',
                                                                     N'',
                                                                     N'',
                                                                     N'" + (Convert.ToDecimal(dt21.Rows[0]["Price"].ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                                                                     N'0',
                                                                     N'00001',
                                                                     N'" + outKtypeid + @"',
                                                                     N'" + inKtypeid + @"',
                                                                     N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                                                                     N'0',
                                                                     N'0',
                                                                     N'0',
                                                                     NULL,
                                                                     N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                                                                     N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                                                                     N'1.0000000000',
                                                                     NULL,
                                                                     N'" + dt21.Rows[0]["Price"].ToString() + @"',
                                                                     N'" + inhuowei + @"',
                                                                     N'" + outhuowei + @"',
                                                                     N'0',
                                                                     N'0',
                                                                     N'0',
                                                                     N'" + (j + 1) + "')";
                    }
                    ssql += "exec Gp_InsertMoveBillDT @details=@p1";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, ssql);


                    result.Type = AjaxResultType.Success;
                    result.Content = "执行成功";
                    result.Data = "";
                    result.TotalRows = 0;
                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "单据成功，但没有商品明细，调拨单生成失败";
                    result.Data = "";
                    result.TotalRows = 0;
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }


        /// <summary>
        /// 变价调拨单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IHttpActionResult CreateAllocationOrderBJ(BaseBillIndexModel model)
        {


            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            //职员ID
            if (string.IsNullOrWhiteSpace(model.Eusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Eusercode不可为空";
                return Json(result);
            }
            //入仓库
            if (string.IsNullOrWhiteSpace(model.InKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }
            //出仓库
            if (string.IsNullOrWhiteSpace(model.OutKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }

            //订单Code
            if (string.IsNullOrWhiteSpace(model.Billcode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Billcode不可为空";
                return Json(result);
            }

            //查询职员ID
            string strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Eusercode);
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();
            string Fullname = dt.Rows[0]["FullName"].ToString();


            //查询入库仓库ID
            string strSQL2 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.InKusercode);
            DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
            if (dt2.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "入库仓库ID不存在";
                return Json(result);
            }
            string inKtypeid = dt2.Rows[0]["typeid"].ToString();



            //查询出库仓库ID
            string strSQL8 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.OutKusercode);
            DataTable dt8 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL8).Tables[0];
            if (dt8.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "出库仓库ID不存在";
                return Json(result);
            }
            string outKtypeid = dt8.Rows[0]["typeid"].ToString();


            //判断商品Billcode是否存在
            string strSQL7 = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Billcode);
            DataTable dt7 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL7).Tables[0];
            if (dt7.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:Billcode已存在";
                return Json(result);
            }
            if (model.CommoditiesDetails.Count > 0)
            {
                foreach (var item in model.CommoditiesDetails)
                {

                    //商品
                    if (string.IsNullOrWhiteSpace(item.Pusercode))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "CommoditiesDetails.Pusercode商品类型code不可为空";
                        return Json(result);
                    }
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + item.InCargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.InCargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + item.OutCargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.OutCargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }

                }

            }
            else
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "未添加商品明细";
                return Json(result);
            }

            decimal pricetotal = 0;
            for (int i = 0; i < model.CommoditiesDetails.Count; i++)
            {
                //查询商品ID
                string strSQL23 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[i].Pusercode.Trim());
                DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];

                if (dt23.Rows.Count > 0)
                {
                    DataTable dt22 = null;
                    string strSQL22 = "";
                    if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[i].Serial))
                    {
                        //仓库表单价
                        strSQL22 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt23.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }
                    else
                    {
                        //序列号表单价
                        strSQL22 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[i].Serial + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }


                    if (dt22.Rows.Count > 0)
                    {
                        pricetotal += (Convert.ToDecimal(dt22.Rows[0]["Price"].ToString()) * model.CommoditiesDetails[i].CQty);
                    }
                    else
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "商品没有录入价格，请完善商品信息在提交:" + model.CommoditiesDetails[i].Pusercode.Trim();
                        return Json(result);
                    }

                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "商品明细有不存在到商品，请检查商品Pusercode参数值是否准确：" + model.CommoditiesDetails[i].Pusercode.Trim();
                    return Json(result);
                }
            }




            try
            {
                decimal totalmoney = 0;//计算总价
                foreach (var item in model.CommoditiesDetails)
                {
                    totalmoney += Convert.ToDecimal(item.CPrice);
                }
                string BillIndexNumberId = "";//单号 

                string nowda = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string code = model.Billcode.ToString();
                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",Convert.ToDateTime(nowda)),//单据日期
                    new SqlParameter("@BillCode",model.Billcode),//单据编码
                    new SqlParameter("@BillType","21"),////单据类型 21变价调拨单
                    new SqlParameter("@Comment", "根据单号【" + code + "】生成调拨单"),//备注
                    new SqlParameter("@ATypeID",""),//会计科目ID  Atype表 0000100006
                    new SqlParameter("@PTypeID",""),//商品ID Ptype表
                    new SqlParameter("@BTypeID", ""),//往来单位ID 暂时默认00001 20220421去掉 00001     
                    new SqlParameter("@ETypeID", Etypeid),//职员ID
                    new SqlParameter("@KTypeID", outKtypeid),//出库仓库ID
                    new SqlParameter("@KTypeID2",inKtypeid),//入库仓库ID   
                    new SqlParameter("@IfCheck", "f"),//是否过账标识 't','f'
                    new SqlParameter("@CheckE",Etypeid),//制单人
                    new SqlParameter("@TotalMoney",totalmoney),//单据金额
                    new SqlParameter("@TotalQty",model.CommoditiesDetails.Sum(p => p.CQty)),//单据数量
                    new SqlParameter("@ntotalmoney", totalmoney),//原币总金额 //合计
                    new SqlParameter("@TotalInMoney",pricetotal),//收款金额
                    new SqlParameter("@Tax","0.0"),//税率0.0
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@ATYPEID1", ""),//往来科目
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount","0"),//是否多账户收(付)款
                    new SqlParameter("@vipczmoney", "0"),//充值前金额
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//会员卡充值前次数 维修的
                    new SqlParameter("@PosBillType","0"),//
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney","0"),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@sharemode","0"),//摊销方式
                    new SqlParameter("@DEALBTYPEID",""),//往来单位 20220421去掉00001
                    new SqlParameter("@cid",1),//外币币种id
                    new SqlParameter("@rate", 1),//汇率
                    new SqlParameter("@ntotalinmoney", "0"),//原币收现金额
                    new SqlParameter("@npreferencemoney", "0"),//原币优惠金额
                    new SqlParameter("@nvipczmoney", "0"),//原币会员卡充值金额
                    new SqlParameter("@billproperty", -1),//单据属性
                    new SqlParameter("@ncompletetotal", "0"),//原币结算金额
                    new SqlParameter("@isini", false),//是否是期初 
                    new SqlParameter("@ATID","0"),//
                    new SqlParameter("@completetotal", "0"),//按单结算金额
                    new SqlParameter("@IfCargo", "0"),//是否启用货位调整
                    new SqlParameter("@IfInvoice","0"),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//
                    new SqlParameter("@WayBillCode", ""),//运单号
                    new SqlParameter("@Goodsnumber", ""),//物件数量 
                    new SqlParameter("@PackWay", ""),//包装方式 
                    new SqlParameter("@Tel", ""),//电话 这个应该是货运公司
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//接件单id
                    new SqlParameter("@JieJianID","-1"),//接件单明细id
                    new SqlParameter("@BaoXiuID","-1"),//报修单明细id
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//报修单id
                   /////////////////////////////////////////////////////////////////
                  
                    new SqlParameter("@OrderID","0"),//订单ID  
                    new SqlParameter("@preferencemoney","0"),//优惠金额 
                    new SqlParameter("@AlertDay", 9999),//收付款日期   
                    new SqlParameter("@VipCardID", -1),//vip卡id 
                    new SqlParameter("@KTypeID3",""),//维修仓库
                    new SqlParameter("@LinkMan", ""),//联系人
                    new SqlParameter("@LinkTel", ""),//联系电话
                    new SqlParameter("@LinkAddr",""),//联系地址
                    new SqlParameter("@wxManID",""),//维修人卡号      
                    new SqlParameter("@BuyDate",""),//会员卡有效期 datetime
                    new SqlParameter("@Serial",  ""),//序列号 
                    new SqlParameter("@wxTotal","0"),// 充值次数,金额 
                    new SqlParameter("@ErrDes",""),//故障描述
                    new SqlParameter("@ifHideJieJian", "0"),//是否隐
                    new SqlParameter("@ifWX","0"),//是否维修单据
                    new SqlParameter("@IfBargainOn","0"),//询价单，报价单成交标志 /// 0:未成交 1:成交
                    new SqlParameter("@FromBillNumberID", "0"),//源单id
                    new SqlParameter("@CostSale","0"),//成本价销售标识
                    new SqlParameter("@uf1",""),////自定义表头字段
                    new SqlParameter("@uf2",""),//
                    new SqlParameter("@uf3",""),//
                    new SqlParameter("@uf4",""),//
                    new SqlParameter("@uf5", ""),//
                    new SqlParameter("@invoicemoney", "0"),//已开票本币金额
                    new SqlParameter("@ninvoicemoney", "0"),//已开票原币金额
                    //new SqlParameter("@importtype", 0),//TINYINT类型
                    new SqlParameter("@AssetBusinessTypeId", "0"),////业务类型id     
                    new SqlParameter("@discount", 1),//折扣
                    new SqlParameter("@checkSave", ""),//
                    new SqlParameter("@chargeoffbtypeid", ""),//
                   // new SqlParameter("@chargeofftype", 0),//
                    new SqlParameter("@chargeofftotal", "0"),//
                    new SqlParameter("@nchargeofftotal", "0"),//
                    new SqlParameter("@IsLend", "0"),//     
                    new SqlParameter("@PromonIds", ""),//
                    new SqlParameter("@isByBrandarType", "0"),//是否启用品牌             
	                new SqlParameter("@promotionmsg", ""),//
                    new SqlParameter("@STypeID2", ""),//
                   // new SqlParameter("@ifconfirm", 0),//
                  //  new SqlParameter("@FeeDeductType", 0),//
                    new SqlParameter("@TransferType", 1),//
                    new SqlParameter("@isyapi", "0"),//
                    new SqlParameter("@yapiorderid","0"),//
                    new SqlParameter("@DeliveryAddress",""),//
                   // new SqlParameter("@AdpriceType", 0),//
                    new SqlParameter("@WarehouseOutDay", 9999),//出库期限
                    new SqlParameter("@StockInDeadline", 9999),//入库期限
                    new SqlParameter("@IsNeedTransport", 0),//是否需要运输配送
                    new SqlParameter("@iscombinationstyle", "0"),//
                    new SqlParameter("@transporterid", "0"),//
                    new SqlParameter("@transporterfullname", ""),//
                    new SqlParameter("@shipperfullname", ""),//
                    new SqlParameter("@shipperperson", ""),//
                    new SqlParameter("@shippertel", ""),//
                    new SqlParameter("@transportno", ""),//
                    new SqlParameter("@totalfreight", "0"),//
                    new SqlParameter("@ntotalfreight","0"),//
                    new SqlParameter("@NewPosBill", 0),//pos上传单据标志
                  //  new SqlParameter("@PayOnTheSpot", 0),//当面付
                    new SqlParameter("@posid", 0),//
                    new SqlParameter("@allowinvoicing", 1)//
     
                };


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                DataTable dt6 = new DataTable();
                string strSQL6 = "";
                strSQL6 += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(code);
                dt6 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL6).Tables[0];
                if (dt6.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                //获取单号
                BillIndexNumberId = dt6.Rows[0]["BillNumberId"].ToString();




                //执行添加调拨明细
                if (model.CommoditiesDetails.Count > 0)
                {
                    string ssql = "declare @p1 dbo.TBType_MoveBjBill ";
                    for (int j = 0; j < model.CommoditiesDetails.Count; j++)
                    {
                        //查询出库货位
                        string strSQL3 = "select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[j].OutCargoCode + "'";
                        DataTable dt3 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        string outhuowei = dt3.Rows[0]["CargoID"].ToString();

                        //查询入库货位
                        string strSQL9 = "select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[j].InCargoCode + "'";
                        DataTable dt9 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL9).Tables[0];
                        string inhuowei = dt9.Rows[0]["CargoID"].ToString();

                        //查询商品ID
                        string strSQL20 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[j].Pusercode.Trim());
                        DataTable dt20 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL20).Tables[0];


                        //查询商品ID

                        DataTable dt21 = null;
                        string strSQL21 = "";
                        if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[j].Serial))
                        {
                            //仓库表单价
                            strSQL21 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt20.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }
                        else
                        {
                            //序列号表单价
                            strSQL21 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[j].Serial + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }

                        ssql += @"insert into @p1 values(N'" + BillIndexNumberId + @"',
                        N'" + dt20.Rows[0]["typeid"].ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CPrice.ToString() + @"',
                        N'" + (Convert.ToDecimal(model.CommoditiesDetails[j].CPrice.ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                        N'',
                        N'0',
                        N'я" + model.CommoditiesDetails[j].Serial.ToString().Replace(",", "я") + @"я',
                        N'0',
                        N'" + dt21.Rows[0]["GoodsNumber"].ToString() + @"',
                        N'" + dt21.Rows[0]["ProduceDate"].ToString() + @"',
                        N'',
                        N'',
                        N'" + dt21.Rows[0]["Price"].ToString() + @"',
                        N'0',
                        N'00001',
                        N'" + outKtypeid + @"',
                        N'" + inKtypeid + @"',
                        N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                        N'0',
                        N'0',
                        N'0',
                        NULL,
                        N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                        N'1.0000000000',
                        NULL,
                        N'" + model.CommoditiesDetails[j].CPrice.ToString() + @"',
                        N'" + inhuowei + @"',
                        N'" + outhuowei + @"',
                        N'0',
                        N'0',
                        N'0',
                        N'" + (j + 1) + "')";

                    }

                    ssql += "exec Gp_InsertMoveBjBillDT @details=@p1";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, ssql);


                    result.Type = AjaxResultType.Success;
                    result.Content = "执行成功";
                    result.Data = "";
                    result.TotalRows = 0;
                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "单据成功，但没有商品明细，调拨单生成失败";
                    result.Data = "";
                    result.TotalRows = 0;
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 同价调拨单-自动过账
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IHttpActionResult CreateAllocationOrderSeed(BaseBillIndexModel model)
        {


            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            //职员ID
            if (string.IsNullOrWhiteSpace(model.Eusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Eusercode不可为空";
                return Json(result);
            }
            //入仓库
            if (string.IsNullOrWhiteSpace(model.InKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }
            //出仓库
            if (string.IsNullOrWhiteSpace(model.OutKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }

            //订单Code
            if (string.IsNullOrWhiteSpace(model.Billcode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Billcode不可为空";
                return Json(result);
            }

            //查询职员ID
            string strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Eusercode);
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();
            string Fullname = dt.Rows[0]["FullName"].ToString();


            //查询入库仓库ID
            string strSQL2 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.InKusercode);
            DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
            if (dt2.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "入库仓库ID不存在";
                return Json(result);
            }
            string inKtypeid = dt2.Rows[0]["typeid"].ToString();



            //查询出库仓库ID
            string strSQL8 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.OutKusercode);
            DataTable dt8 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL8).Tables[0];
            if (dt8.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "出库仓库ID不存在";
                return Json(result);
            }
            string outKtypeid = dt8.Rows[0]["typeid"].ToString();


            //判断商品Billcode是否存在
            string strSQL7 = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Billcode);
            DataTable dt7 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL7).Tables[0];
            if (dt7.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:Billcode已存在";
                return Json(result);
            }
            if (model.CommoditiesDetails.Count > 0)
            {
                foreach (var item in model.CommoditiesDetails)
                {

                    //商品
                    if (string.IsNullOrWhiteSpace(item.Pusercode))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "CommoditiesDetails.Pusercode商品类型code不可为空";
                        return Json(result);
                    }
                }

            }
            else
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "未添加商品明细";
                return Json(result);
            }

            decimal pricetotal = 0;
            for (int i = 0; i < model.CommoditiesDetails.Count; i++)
            {
                //查询商品ID
                string strSQL23 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[i].Pusercode.Trim());
                DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];

                if (dt23.Rows.Count > 0)
                {

                    DataTable dt22 = null;
                    string strSQL22 = "";
                    if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[i].Serial))
                    {
                        //仓库表单价
                        strSQL22 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt23.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }
                    else
                    {
                        //序列号表单价
                        strSQL22 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[i].Serial + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }

                    if (dt22.Rows.Count > 0)
                    {
                        pricetotal += (Convert.ToDecimal(dt22.Rows[0]["Price"].ToString()) * model.CommoditiesDetails[i].CQty);
                    }
                    else
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "商品没有录入价格，请完善商品Pusercode基本信息:" + model.CommoditiesDetails[i].Pusercode.Trim();
                        return Json(result);
                    }

                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "商品明细有不存在的商品，请检查商品Pusercode参数值是否准确：" + model.CommoditiesDetails[i].Pusercode.Trim();
                    return Json(result);
                }
                if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[i].InCargoCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "CargoCode[" + model.CommoditiesDetails[i].InCargoCode + "]不存在，或此仓库没有这个货位";
                    return Json(result);
                }
                if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[i].OutCargoCode + "'"))
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "CargoCode[" + model.CommoditiesDetails[i].OutCargoCode + "]不存在，或此仓库没有这个货位";
                    return Json(result);
                }

            }




            try
            {

                string BillIndexNumberId = "";//单号 

                string nowda = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string code = model.Billcode.ToString();
                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",Convert.ToDateTime(nowda)),//单据日期
                    new SqlParameter("@BillCode",model.Billcode),//单据编码
                    new SqlParameter("@BillType","17"),////单据类型 17调拨单
                    new SqlParameter("@Comment", "根据单号【" + code + "】生成调拨单"),//备注
                    new SqlParameter("@ATypeID",""),//会计科目ID  Atype表 0000100006
                    new SqlParameter("@PTypeID",""),//商品ID Ptype表
                    new SqlParameter("@BTypeID", ""),//往来单位ID 暂时默认00001 20220421去掉 00001     
                    new SqlParameter("@ETypeID", Etypeid),//职员ID
                    new SqlParameter("@KTypeID", outKtypeid),//出库仓库ID
                    new SqlParameter("@KTypeID2",inKtypeid),//入库仓库ID   
                    new SqlParameter("@IfCheck", "f"),//是否过账标识 't','f'
                    new SqlParameter("@CheckE",Etypeid),//制单人
                    new SqlParameter("@TotalMoney","0"),//单据金额
                    new SqlParameter("@TotalQty",model.CommoditiesDetails.Sum(p => p.CQty)),//单据数量
                    new SqlParameter("@ntotalmoney", "0"),//原币总金额 //合计
                    new SqlParameter("@TotalInMoney",pricetotal),//收款金额
                    new SqlParameter("@Tax","0.0"),//税率0.0
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@ATYPEID1", ""),//往来科目
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount","0"),//是否多账户收(付)款
                    new SqlParameter("@vipczmoney", "0"),//充值前金额
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//会员卡充值前次数 维修的
                    new SqlParameter("@PosBillType","0"),//
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney","0"),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@sharemode","0"),//摊销方式
                    new SqlParameter("@DEALBTYPEID",""),//往来单位 20220421去掉00001
                    new SqlParameter("@cid",1),//外币币种id
                    new SqlParameter("@rate", 1),//汇率
                    new SqlParameter("@ntotalinmoney", "0"),//原币收现金额
                    new SqlParameter("@npreferencemoney", "0"),//原币优惠金额
                    new SqlParameter("@nvipczmoney", "0"),//原币会员卡充值金额
                    new SqlParameter("@billproperty", -1),//单据属性
                    new SqlParameter("@ncompletetotal", "0"),//原币结算金额
                    new SqlParameter("@isini", false),//是否是期初 
                    new SqlParameter("@ATID","0"),//
                    new SqlParameter("@completetotal", "0"),//按单结算金额
                    new SqlParameter("@IfCargo", "0"),//是否启用货位调整
                    new SqlParameter("@IfInvoice","0"),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//
                    new SqlParameter("@WayBillCode", ""),//运单号
                    new SqlParameter("@Goodsnumber", ""),//物件数量 
                    new SqlParameter("@PackWay", ""),//包装方式 
                    new SqlParameter("@Tel", ""),//电话 这个应该是货运公司
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//接件单id
                    new SqlParameter("@JieJianID","-1"),//接件单明细id
                    new SqlParameter("@BaoXiuID","-1"),//报修单明细id
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//报修单id
                   /////////////////////////////////////////////////////////////////
                  
                    new SqlParameter("@OrderID","0"),//订单ID  
                    new SqlParameter("@preferencemoney","0"),//优惠金额 
                    new SqlParameter("@AlertDay", 9999),//收付款日期   
                    new SqlParameter("@VipCardID", -1),//vip卡id 
                    new SqlParameter("@KTypeID3",""),//维修仓库
                    new SqlParameter("@LinkMan", ""),//联系人
                    new SqlParameter("@LinkTel", ""),//联系电话
                    new SqlParameter("@LinkAddr",""),//联系地址
                    new SqlParameter("@wxManID",""),//维修人卡号      
                    new SqlParameter("@BuyDate",""),//会员卡有效期 datetime
                    new SqlParameter("@Serial",  ""),//序列号 
                    new SqlParameter("@wxTotal","0"),// 充值次数,金额 
                    new SqlParameter("@ErrDes",""),//故障描述
                    new SqlParameter("@ifHideJieJian", "0"),//是否隐
                    new SqlParameter("@ifWX","0"),//是否维修单据
                    new SqlParameter("@IfBargainOn","0"),//询价单，报价单成交标志 /// 0:未成交 1:成交
                    new SqlParameter("@FromBillNumberID", "0"),//源单id
                    new SqlParameter("@CostSale","0"),//成本价销售标识
                    new SqlParameter("@uf1",""),////自定义表头字段
                    new SqlParameter("@uf2",""),//
                    new SqlParameter("@uf3",""),//
                    new SqlParameter("@uf4",""),//
                    new SqlParameter("@uf5", ""),//
                    new SqlParameter("@invoicemoney", "0"),//已开票本币金额
                    new SqlParameter("@ninvoicemoney", "0"),//已开票原币金额
                    //new SqlParameter("@importtype", 0),//TINYINT类型
                    new SqlParameter("@AssetBusinessTypeId", "0"),////业务类型id     
                    new SqlParameter("@discount", 1),//折扣
                    new SqlParameter("@checkSave", ""),//
                    new SqlParameter("@chargeoffbtypeid", ""),//
                   // new SqlParameter("@chargeofftype", 0),//
                    new SqlParameter("@chargeofftotal", "0"),//
                    new SqlParameter("@nchargeofftotal", "0"),//
                    new SqlParameter("@IsLend", "0"),//     
                    new SqlParameter("@PromonIds", ""),//
                    new SqlParameter("@isByBrandarType", "0"),//是否启用品牌             
	                new SqlParameter("@promotionmsg", ""),//
                    new SqlParameter("@STypeID2", ""),//
                   // new SqlParameter("@ifconfirm", 0),//
                  //  new SqlParameter("@FeeDeductType", 0),//
                    new SqlParameter("@TransferType", 1),//
                    new SqlParameter("@isyapi", "0"),//
                    new SqlParameter("@yapiorderid","0"),//
                    new SqlParameter("@DeliveryAddress",""),//
                   // new SqlParameter("@AdpriceType", 0),//
                    new SqlParameter("@WarehouseOutDay", 9999),//出库期限
                    new SqlParameter("@StockInDeadline", 9999),//入库期限
                    new SqlParameter("@IsNeedTransport", 0),//是否需要运输配送
                    new SqlParameter("@iscombinationstyle", "0"),//
                    new SqlParameter("@transporterid", "0"),//
                    new SqlParameter("@transporterfullname", ""),//
                    new SqlParameter("@shipperfullname", ""),//
                    new SqlParameter("@shipperperson", ""),//
                    new SqlParameter("@shippertel", ""),//
                    new SqlParameter("@transportno", ""),//
                    new SqlParameter("@totalfreight", "0"),//
                    new SqlParameter("@ntotalfreight","0"),//
                    new SqlParameter("@NewPosBill", 0),//pos上传单据标志
                  //  new SqlParameter("@PayOnTheSpot", 0),//当面付
                    new SqlParameter("@posid", 0),//
                    new SqlParameter("@allowinvoicing", 1)//
     
                };


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                DataTable dt6 = new DataTable();
                string strSQL6 = "";
                strSQL6 += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(code);
                dt6 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL6).Tables[0];
                if (dt6.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                //获取单号
                BillIndexNumberId = dt6.Rows[0]["BillNumberId"].ToString();




                //执行添加调拨明细
                if (model.CommoditiesDetails.Count > 0)
                {
                    string ssql = "declare @p1 dbo.TBType_MoveBill ";
                    for (int j = 0; j < model.CommoditiesDetails.Count; j++)
                    {
                        //查询出库货位
                        string strSQL3 = "select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[j].OutCargoCode + "'";
                        DataTable dt3 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        string outhuowei = dt3.Rows[0]["CargoID"].ToString();

                        //查询入库货位
                        string strSQL9 = "select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[j].InCargoCode + "'";
                        DataTable dt9 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL9).Tables[0];
                        string inhuowei = dt9.Rows[0]["CargoID"].ToString();


                        //查询商品ID
                        string strSQL20 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[j].Pusercode.Trim());
                        DataTable dt20 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL20).Tables[0];


                        //查询商品ID

                        DataTable dt21 = null;
                        string strSQL21 = "";
                        if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[j].Serial))
                        {
                            //仓库表单价
                            strSQL21 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt20.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }
                        else
                        {
                            //序列号表单价
                            strSQL21 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[j].Serial + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }



                        ssql += @"insert into @p1 values(N'" + BillIndexNumberId + @"',
                                                                     N'" + dt20.Rows[0]["typeid"].ToString() + @"',
                                                                     N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                                                                     N'" + dt21.Rows[0]["Price"].ToString() + @"',
                                                                     N'" + (Convert.ToDecimal(dt21.Rows[0]["Price"].ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                                                                     N'',
                                                                     N'0',
                                                                     N'я" + model.CommoditiesDetails[j].Serial.ToString().Replace(",", "я") + @"я',
                                                                     N'0',
                                                                     N'" + dt21.Rows[0]["GoodsNumber"].ToString() + @"',
                                                                     N'" + dt21.Rows[0]["ProduceDate"].ToString() + @"',
                                                                     N'',
                                                                     N'',
                                                                     N'" + (Convert.ToDecimal(dt21.Rows[0]["Price"].ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                                                                     N'0',
                                                                     N'00001',
                                                                     N'" + outKtypeid + @"',
                                                                     N'" + inKtypeid + @"',
                                                                     N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                                                                     N'0',
                                                                     N'0',
                                                                     N'0',
                                                                     NULL,
                                                                     N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                                                                     N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                                                                     N'1.0000000000',
                                                                     NULL,
                                                                     N'" + dt21.Rows[0]["Price"].ToString() + @"',
                                                                     N'" + inhuowei + @"',
                                                                     N'" + outhuowei + @"',
                                                                     N'0',
                                                                     N'0',
                                                                     N'0',
                                                                     N'" + (j + 1) + "')";
                    }
                    ssql += "exec Gp_InsertMoveBillDT @details=@p1";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, ssql);




                    //直接过账 YUANYE 2022-07-26

                    SqlParameter[] parmsyy = {
                    new SqlParameter("@nBillID",BillIndexNumberId),//单号
                    new SqlParameter("@szCheckMan","00001"),//制单人
                    new SqlParameter("@chvOpID",Etypeid),//当前操作员
                    new SqlParameter("@billtype","17"),//单据类型
                    new SqlParameter("@szPID",""),
                    new SqlParameter("@Ret",0)  };

                    parmsyy[4].Direction = ParameterDirection.Output;
                    parmsyy[5].Direction = ParameterDirection.Output;

                    int ii = 0;
                    FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_NewAuditing", parmsyy, out ii);

                    string pr = parmsyy[5].Value.ToString();




                    if (pr == "0")
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "成功";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                    else
                    {
                        result.Type = AjaxResultType.Fail;
                        result.Content = "草稿生成成功,但过账失败！";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                }
                else
                {
                    result.Type = AjaxResultType.Fail;
                    result.Content = "单据成功，但没有商品明细，调拨单生成失败";
                    result.Data = "";
                    result.TotalRows = 0;
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }


        /// <summary>
        /// 变价调拨单-自动过账
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public IHttpActionResult CreateAllocationOrderBJSeed(BaseBillIndexModel model)
        {


            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                return Json(result);
            }
            FreeADO.DBUtility.DbHelperSQLP db = new FreeADO.DBUtility.DbHelperSQLP(connectionString);
            //职员ID
            if (string.IsNullOrWhiteSpace(model.Eusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Eusercode不可为空";
                return Json(result);
            }
            //入仓库
            if (string.IsNullOrWhiteSpace(model.InKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }
            //出仓库
            if (string.IsNullOrWhiteSpace(model.OutKusercode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "InKusercode不可为空";
                return Json(result);
            }

            //订单Code
            if (string.IsNullOrWhiteSpace(model.Billcode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "Billcode不可为空";
                return Json(result);
            }

            //查询职员ID
            string strSQL = "select typeid,DtypeID,FullName from employee where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Eusercode);
            DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];
            if (dt.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "职员ID不存在";
                return Json(result);
            }
            string Etypeid = dt.Rows[0]["typeid"].ToString();
            string Dtypeid = dt.Rows[0]["DtypeID"].ToString();
            string Fullname = dt.Rows[0]["FullName"].ToString();


            //查询入库仓库ID
            string strSQL2 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.InKusercode);
            DataTable dt2 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL2).Tables[0];
            if (dt2.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "入库仓库ID不存在";
                return Json(result);
            }
            string inKtypeid = dt2.Rows[0]["typeid"].ToString();



            //查询出库仓库ID
            string strSQL8 = "select typeid from stock where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.OutKusercode);
            DataTable dt8 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL8).Tables[0];
            if (dt8.Rows.Count <= 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "出库仓库ID不存在";
                return Json(result);
            }
            string outKtypeid = dt8.Rows[0]["typeid"].ToString();


            //判断商品Billcode是否存在
            string strSQL7 = "select BillCode from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.Billcode);
            DataTable dt7 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL7).Tables[0];
            if (dt7.Rows.Count > 0)
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "销售单ID:Billcode已存在";
                return Json(result);
            }
            if (model.CommoditiesDetails.Count > 0)
            {
                foreach (var item in model.CommoditiesDetails)
                {

                    //商品
                    if (string.IsNullOrWhiteSpace(item.Pusercode))
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "CommoditiesDetails.Pusercode商品类型code不可为空";
                        return Json(result);
                    }
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + item.InCargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.InCargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }
                    if (!db.Exists("select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + item.OutCargoCode + "'"))
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "CargoCode[" + item.OutCargoCode + "]不存在，或此仓库没有这个货位";
                        return Json(result);
                    }

                }

            }
            else
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "未添加商品明细";
                return Json(result);
            }

            decimal pricetotal = 0;
            for (int i = 0; i < model.CommoditiesDetails.Count; i++)
            {
                //查询商品ID
                string strSQL23 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[i].Pusercode.Trim());
                DataTable dt23 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL23).Tables[0];

                if (dt23.Rows.Count > 0)
                {
                    DataTable dt22 = null;
                    string strSQL22 = "";
                    if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[i].Serial))
                    {
                        //仓库表单价
                        strSQL22 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt23.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }
                    else
                    {
                        //序列号表单价
                        strSQL22 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[i].Serial + "'";
                        dt22 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL22).Tables[0];
                    }


                    if (dt22.Rows.Count > 0)
                    {
                        pricetotal += (Convert.ToDecimal(dt22.Rows[0]["Price"].ToString()) * model.CommoditiesDetails[i].CQty);
                    }
                    else
                    {
                        result.Type = AjaxResultType.Warning;
                        result.Content = "商品没有录入价格，请完善商品信息在提交:" + model.CommoditiesDetails[i].Pusercode.Trim();
                        return Json(result);
                    }

                }
                else
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "商品明细有不存在到商品，请检查商品Pusercode参数值是否准确：" + model.CommoditiesDetails[i].Pusercode.Trim();
                    return Json(result);
                }
            }




            try
            {

                decimal totalmoney = 0;//计算总价
                foreach (var item in model.CommoditiesDetails)
                {
                    totalmoney += Convert.ToDecimal(item.CPrice);
                }

                string BillIndexNumberId = "";//单号 

                string nowda = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string code = model.Billcode.ToString();
                SqlParameter[] parameters = {
                    new SqlParameter("@BillDate",Convert.ToDateTime(nowda)),//单据日期
                    new SqlParameter("@BillCode",model.Billcode),//单据编码
                    new SqlParameter("@BillType","21"),////单据类型 21变价调拨单
                    new SqlParameter("@Comment", "根据单号【" + code + "】生成调拨单"),//备注
                    new SqlParameter("@ATypeID",""),//会计科目ID  Atype表 0000100006
                    new SqlParameter("@PTypeID",""),//商品ID Ptype表
                    new SqlParameter("@BTypeID", ""),//往来单位ID 暂时默认00001 20220421去掉 00001     
                    new SqlParameter("@ETypeID", Etypeid),//职员ID
                    new SqlParameter("@KTypeID", outKtypeid),//出库仓库ID
                    new SqlParameter("@KTypeID2",inKtypeid),//入库仓库ID   
                    new SqlParameter("@IfCheck", "f"),//是否过账标识 't','f'
                    new SqlParameter("@CheckE","00001"),//制单人
                    new SqlParameter("@TotalMoney",totalmoney),//单据金额
                    new SqlParameter("@TotalQty",model.CommoditiesDetails.Sum(p => p.CQty)),//单据数量
                    new SqlParameter("@ntotalmoney",totalmoney),//原币总金额 //合计
                    new SqlParameter("@TotalInMoney",pricetotal),//收款金额
                    new SqlParameter("@Tax","0.0"),//税率0.0
                    new SqlParameter("@szPeriod",1),//会计期间
                    new SqlParameter("@Explain",""),//说明
                    new SqlParameter("@Draft",'1'),//草稿标识
                    new SqlParameter("@RedWord",'0'),//红冲标识
                    new SqlParameter("@STypeID","00001"),//分支机构ID
                    new SqlParameter("@DTypeID",Dtypeid),//部门ID
                    new SqlParameter("@ATYPEID1", ""),//往来科目
                    new SqlParameter("@completedate",null),//
                    new SqlParameter("@billstate",1),//
                    new SqlParameter("@ifmulaccount","0"),//是否多账户收(付)款
                    new SqlParameter("@vipczmoney", "0"),//充值前金额
                    new SqlParameter("@otherinouttype",-1),//
                    new SqlParameter("@czbeforetimes",0),//会员卡充值前次数 维修的
                    new SqlParameter("@PosBillType","0"),//
                    new SqlParameter("@TransportId",""),//
                    new SqlParameter("@IsFreightMoney","0"),//
                    new SqlParameter("@FreightAddr",null),//
                    new SqlParameter("@FreightPerson",null),//
                    new SqlParameter("@FreightTel",null),//
                    new SqlParameter("@sharemode","0"),//摊销方式
                    new SqlParameter("@DEALBTYPEID",""),//往来单位 20220421去掉00001
                    new SqlParameter("@cid",1),//外币币种id
                    new SqlParameter("@rate", 1),//汇率
                    new SqlParameter("@ntotalinmoney", "0"),//原币收现金额
                    new SqlParameter("@npreferencemoney", "0"),//原币优惠金额
                    new SqlParameter("@nvipczmoney", "0"),//原币会员卡充值金额
                    new SqlParameter("@billproperty", -1),//单据属性
                    new SqlParameter("@ncompletetotal", "0"),//原币结算金额
                    new SqlParameter("@isini", false),//是否是期初 
                    new SqlParameter("@ATID","0"),//
                    new SqlParameter("@completetotal", "0"),//按单结算金额
                    new SqlParameter("@IfCargo", "0"),//是否启用货位调整
                    new SqlParameter("@IfInvoice","0"),//
                    new SqlParameter("@promoruleid",'0'),//
                    new SqlParameter("@beforepromobillnumberid",'0'),//
                    new SqlParameter("@WayBillCode", ""),//运单号
                    new SqlParameter("@Goodsnumber", ""),//物件数量 
                    new SqlParameter("@PackWay", ""),//包装方式 
                    new SqlParameter("@Tel", ""),//电话 这个应该是货运公司
                    new SqlParameter("@Assessor",""),//
                    new SqlParameter("@IfAudit",""),//
                    new SqlParameter("@Audit_explain",""),//
                    new SqlParameter("@JieJianBillNumberID","-1"),//接件单id
                    new SqlParameter("@JieJianID","-1"),//接件单明细id
                    new SqlParameter("@BaoXiuID","-1"),//报修单明细id
                    new SqlParameter("@BaoXiuBillNumberID","-1"),//报修单id
                   /////////////////////////////////////////////////////////////////
                  
                    new SqlParameter("@OrderID","0"),//订单ID  
                    new SqlParameter("@preferencemoney","0"),//优惠金额 
                    new SqlParameter("@AlertDay", 9999),//收付款日期   
                    new SqlParameter("@VipCardID", -1),//vip卡id 
                    new SqlParameter("@KTypeID3",""),//维修仓库
                    new SqlParameter("@LinkMan", ""),//联系人
                    new SqlParameter("@LinkTel", ""),//联系电话
                    new SqlParameter("@LinkAddr",""),//联系地址
                    new SqlParameter("@wxManID",""),//维修人卡号      
                    new SqlParameter("@BuyDate",""),//会员卡有效期 datetime
                    new SqlParameter("@Serial",  ""),//序列号 
                    new SqlParameter("@wxTotal","0"),// 充值次数,金额 
                    new SqlParameter("@ErrDes",""),//故障描述
                    new SqlParameter("@ifHideJieJian", "0"),//是否隐
                    new SqlParameter("@ifWX","0"),//是否维修单据
                    new SqlParameter("@IfBargainOn","0"),//询价单，报价单成交标志 /// 0:未成交 1:成交
                    new SqlParameter("@FromBillNumberID", "0"),//源单id
                    new SqlParameter("@CostSale","0"),//成本价销售标识
                    new SqlParameter("@uf1",""),////自定义表头字段
                    new SqlParameter("@uf2",""),//
                    new SqlParameter("@uf3",""),//
                    new SqlParameter("@uf4",""),//
                    new SqlParameter("@uf5", ""),//
                    new SqlParameter("@invoicemoney", "0"),//已开票本币金额
                    new SqlParameter("@ninvoicemoney", "0"),//已开票原币金额
                    //new SqlParameter("@importtype", 0),//TINYINT类型
                    new SqlParameter("@AssetBusinessTypeId", "0"),////业务类型id     
                    new SqlParameter("@discount", 1),//折扣
                    new SqlParameter("@checkSave", ""),//
                    new SqlParameter("@chargeoffbtypeid", ""),//
                   // new SqlParameter("@chargeofftype", 0),//
                    new SqlParameter("@chargeofftotal", "0"),//
                    new SqlParameter("@nchargeofftotal", "0"),//
                    new SqlParameter("@IsLend", "0"),//     
                    new SqlParameter("@PromonIds", ""),//
                    new SqlParameter("@isByBrandarType", "0"),//是否启用品牌             
	                new SqlParameter("@promotionmsg", ""),//
                    new SqlParameter("@STypeID2", ""),//
                   // new SqlParameter("@ifconfirm", 0),//
                  //  new SqlParameter("@FeeDeductType", 0),//
                    new SqlParameter("@TransferType", 1),//
                    new SqlParameter("@isyapi", "0"),//
                    new SqlParameter("@yapiorderid","0"),//
                    new SqlParameter("@DeliveryAddress",""),//
                   // new SqlParameter("@AdpriceType", 0),//
                    new SqlParameter("@WarehouseOutDay", 9999),//出库期限
                    new SqlParameter("@StockInDeadline", 9999),//入库期限
                    new SqlParameter("@IsNeedTransport", 0),//是否需要运输配送
                    new SqlParameter("@iscombinationstyle", "0"),//
                    new SqlParameter("@transporterid", ""),//
                    new SqlParameter("@transporterfullname", ""),//
                    new SqlParameter("@shipperfullname", ""),//
                    new SqlParameter("@shipperperson", ""),//
                    new SqlParameter("@shippertel", ""),//
                    new SqlParameter("@transportno", ""),//
                    new SqlParameter("@totalfreight", "0"),//
                    new SqlParameter("@ntotalfreight","0"),//
                    new SqlParameter("@NewPosBill", 0),//pos上传单据标志
                  //  new SqlParameter("@PayOnTheSpot", 0),//当面付
                    new SqlParameter("@posid", 0),//
                    new SqlParameter("@allowinvoicing", 1)//
     
                };


                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_InsertBillIndex", parameters, out resultCount);

                DataTable dt6 = new DataTable();
                string strSQL6 = "";
                strSQL6 += "select BillNumberId from BillIndex where BillCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(code);
                dt6 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL6).Tables[0];
                if (dt6.Rows.Count <= 0)
                {
                    result.Type = AjaxResultType.Warning;
                    result.Content = "销售出库单插入错误";
                    return Json(result);
                }

                //获取单号
                BillIndexNumberId = dt6.Rows[0]["BillNumberId"].ToString();




                //执行添加调拨明细
                if (model.CommoditiesDetails.Count > 0)
                {
                    string ssql = "declare @p1 dbo.TBType_MoveBjBill ";
                    for (int j = 0; j < model.CommoditiesDetails.Count; j++)
                    {
                        //查询出库货位
                        string strSQL3 = "select CargoID from CargoType where deleted=0 and KtypeID='" + outKtypeid + "' and Comment='" + model.CommoditiesDetails[j].OutCargoCode + "'";
                        DataTable dt3 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL3).Tables[0];
                        string outhuowei = dt3.Rows[0]["CargoID"].ToString();

                        //查询入库货位
                        string strSQL9 = "select CargoID from CargoType where deleted=0 and KtypeID='" + inKtypeid + "' and Comment='" + model.CommoditiesDetails[j].InCargoCode + "'";
                        DataTable dt9 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL9).Tables[0];
                        string inhuowei = dt9.Rows[0]["CargoID"].ToString();

                        //查询商品ID
                        string strSQL20 = "select typeid,baseUnitId from ptype where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(model.CommoditiesDetails[j].Pusercode.Trim());
                        DataTable dt20 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL20).Tables[0];


                        //查询商品ID

                        DataTable dt21 = null;
                        string strSQL21 = "";
                        if (string.IsNullOrWhiteSpace(model.CommoditiesDetails[j].Serial))
                        {
                            //仓库表单价
                            strSQL21 = "select Price,GoodsNumber,GoodsOrder,ProduceDate from GoodsStocks where PtypeId = '" + dt20.Rows[0]["typeid"].ToString() + "' and KtypeId = '" + outKtypeid + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }
                        else
                        {
                            //序列号表单价
                            strSQL21 = "select CostPrice as Price,GoodsNumber,GoodsOrder,ProduceDate from gp_CruPtypeSerial where Serial='" + model.CommoditiesDetails[j].Serial + "'";
                            dt21 = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL21).Tables[0];
                        }

                        ssql += @"insert into @p1 values(N'" + BillIndexNumberId + @"',
                        N'" + dt20.Rows[0]["typeid"].ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CPrice.ToString() + @"',
                        N'" + (Convert.ToDecimal(model.CommoditiesDetails[j].CPrice.ToString()) * Convert.ToInt32(model.CommoditiesDetails[j].CQty.ToString())) + @"',
                        N'',
                        N'0',
                        N'я" + model.CommoditiesDetails[j].Serial.ToString().Replace(",", "я") + @"я',
                        N'0',
                        N'" + dt21.Rows[0]["GoodsNumber"].ToString() + @"',
                        N'" + dt21.Rows[0]["ProduceDate"].ToString() + @"',
                        N'',
                        N'',
                        N'" + dt21.Rows[0]["Price"].ToString() + @"',
                        N'0',
                        N'00001',
                        N'" + outKtypeid + @"',
                        N'" + inKtypeid + @"',
                        N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                        N'0',
                        N'0',
                        N'0',
                        NULL,
                        N'" + dt20.Rows[0]["baseUnitId"].ToString() + @"',
                        N'" + model.CommoditiesDetails[j].CQty.ToString() + @"',
                        N'1.0000000000',
                        NULL,
                        N'" + model.CommoditiesDetails[j].CPrice.ToString() + @"',
                        N'" + inhuowei + @"',
                        N'" + outhuowei + @"',
                        N'0',
                        N'0',
                        N'0',
                        N'-" + (j + 1) + "')";

                    }

                    ssql += "exec Gp_InsertMoveBjBillDT @details=@p1";
                    FreeADO.DBUtility.DbHelperSQL.ExecuteSqlConnstr(connectionString, ssql);


                    //直接过账 YUANYE 2022-07-27

                    SqlParameter[] parmsyy = {
                    new SqlParameter("@nBillID",BillIndexNumberId),//单号
                    new SqlParameter("@szCheckMan","00001"),//制单人
                    new SqlParameter("@chvOpID",Etypeid),//当前操作员
                    new SqlParameter("@billtype","21"),//单据类型
                    new SqlParameter("@szPID",""),
                    new SqlParameter("@Ret",0)  };

                    parmsyy[4].Direction = ParameterDirection.Output;
                    parmsyy[5].Direction = ParameterDirection.Output;

                    int ii = 0;
                    FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString, "Gp_NewAuditing", parmsyy, out ii);

                    string pr = parmsyy[5].Value.ToString();



                    if (pr == "0")
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "成功";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                    else
                    {
                        result.Type = AjaxResultType.Fail;
                        result.Content = "草稿生成成功,但过账失败！";
                        result.Data = pr;
                        result.TotalRows = 0;
                    }
                }
                else
                {
                    result.Type = AjaxResultType.Fail;
                    result.Content = "单据成功，但没有商品明细，调拨单生成失败";
                    result.Data = "";
                    result.TotalRows = 0;
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }
    }
}